<template>
  <div class="yearPicker" ref="yearPicker" :width="width">
    <input
      class="_inner"
      ref="inputLeft"
      v-model="startShowYear"
      @focus="onFocus"
      @blur="onBlur"
      type="text"
      name="yearInput"
      @keyup="checkStartInput($event)"
      placeholder="选择年份"
    />
    <span>{{ sp }}</span>
    <input
      class="_inner"
      ref="inputRight"
      v-model="endShowYear"
      @focus="onFocus"
      @blur="onBlur"
      type="text"
      name="yearInput"
      @keyup="checkEndInput($event)"
      placeholder="选择年份"
    />
    <!-- <i class="dateIcon el-icon-date"></i> 按照自己标准库里面的图标设置-->
    <span class="_inner labelText">{{ labelText }}</span>
    <div class="_inner floatPanel" v-if="showPanel">
      <div class="_inner leftPanel">
        <div class="_inner panelHead">
          <i class="_inner el-icon-d-arrow-left" @click="onClickLeft"
          >&lt;&lt;</i
          >
          {{ leftYearList[0] + "-" + leftYearList[9] }}
        </div>
        <div class="_inner panelContent">
          <div
            :class="{
              oneSelected: item === beginTime && oneSelected,
              startSelected: item === beginTime,
              endSelected: item === endTime,
              betweenSelected: item > beginTime && item < endTime,
            }"
            v-for="item in leftYearList"
            :key="item"
          >
            <a
              :class="{
                cell: true,
                _inner: true,
                selected: item === beginTime || item === endTime,
              }"
              @click="onClickItem(item)"
              @mouseover="onHoverItem(item)"
            >
              {{ item }}
            </a>
          </div>
        </div>
      </div>
      <div class="_inner rightPanel">
        <div class="_inner panelHead">
          <i class="_inner el-icon-d-arrow-right" @click="onClickRight"
          >&gt;&gt;</i
          >
          {{ rightYearList[0] + "-" + rightYearList[9] }}
        </div>
        <div class="_inner panelContent">
          <div
            :class="{
              startSelected: item === beginTime,
              endSelected: item === endTime,
              betweenSelected: item > beginTime && item < endTime,
            }"
            v-for="item in rightYearList"
            :key="item"
          >
            <a
              :class="{
                cell: true,
                _inner: true,
                selected: item === endTime || item === beginTime,
              }"
              @click="onClickItem(item)"
              @mouseover="onHoverItem(item)"
            >
              {{ item }}
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import moment from "moment";
  const SELECT_STATE = {
    unselect: 0,
    selecting: 1,
    selected: 2,
  };
  export default {
    name: "yearPicker",
    computed: {
      oneSelected() {
        return (
          this.curState === SELECT_STATE.selecting &&
          (this.beginTime === this.endTime || this.endTime == null)
        );
      },
      startDate() {
        return this.beginTime;
      },
      leftYearList() {
        return this.yearList.slice(0, 10);
      },
      rightYearList() {
        return this.yearList.slice(10, 20);
      },
      startYearFormat() {
        if (this._.isNil(this.beginTime)) {
          return null;
        }
        return moment(this.beginTime).startOf("year").format("yyyy");
      },
      endYearFormat() {
        if (this._.isNil(this.endTime)) {
          return null;
        }
        return moment(this.endTime).endOf("year").format("yyyy");
      },
    },
    props: {
      width: {
        default: 200,
      },
      labelWidth: {
        default: 80,
      },
      labelText: {
        default: "时间标签",
      },
      sp: {
        default: "至",
      },
      initYear: {
        default: null,
      },
    },
    data() {
      return {
        itemBg: {},
        startShowYear: null,
        endShowYear: null,
        yearList: [],
        showPanel: false,
        beginTime: null,
        endTime: null,
        curYear: 0,
        curSelectedYear: 0,
        curState: SELECT_STATE.unselect,
      };
    },
    methods: {
      checkStartInput(event) {
        if (isNaN(this.startShowYear)) {
          this.startShowYear = this.beginTime;
        } else {
          this.beginTime = this.startShowYear * 1;
          this.changeYear();
        }
      },

      checkEndInput() {
        if (isNaN(this.endShowYear)) {
          this.endShowYear = this.endTime;
        } else {
          this.endTime = this.endShowYear * 1;
          this.changeYear();
        }
      },
      changeYear() {
        if (this.beginTime > this.endTime) {
          let tmp = this.endTime;
          this.endTime = this.beginTime;
          this.beginTime = tmp;
          this.startShowYear = this.beginTime;
          this.endShowYear = this.endTime;
        }
        if (this.beginTime && this.endTime) {
          this.$emit("updateTimeRange", {
            beginTime: moment(this.beginTime + "")
              .startOf("year")
              .valueOf(),
            endTime:
              moment(this.endTime + "")
                .endOf("year")
                .valueOf() + 1,
          });
        } else {
          console.warn("WARN:年份不合法", this.beginTime, this.endTime);
        }
      },
      onHoverItem(iYear) {
        if (this.curState === SELECT_STATE.selecting) {
          let tmpStart = this.curSelectedYear;
          this.endTime = Math.max(tmpStart, iYear);
          this.beginTime = Math.min(tmpStart, iYear);
        }
      },
      onClickItem(iYear) {
        if (
          this.curState === SELECT_STATE.unselect ||
          this.curState === SELECT_STATE.selected
        ) {
          this.beginTime = iYear;
          this.curSelectedYear = iYear;
          this.endTime = null;
          this.curState = SELECT_STATE.selecting;
        } else if (this.curState === SELECT_STATE.selecting) {
          this.endShowYear = this.endTime;
          this.startShowYear = this.beginTime;
          this.curState = SELECT_STATE.selected;
          this.$emit("updateTimeRange", {
            beginTime: moment(this.beginTime + "")
              .startOf("year")
              .valueOf(),
            endTime:
              moment(this.endTime + "")
                .endOf("year")
                .valueOf() + 1,
          });

          setTimeout(() => {
            //为动画留的时间，可优化
            this.showPanel = false;
          }, 300);
        }
      },
      onFocus() {
        this.$nextTick(() => {
          this.showPanel = true;
        });
      },
      onBlur() {
        //   this.showPanel = false;
      },
      updateYearList() {
        let iStart = Math.floor(this.curYear / 10) * 10 - 10;
        iStart = iStart < 0 ? 0 : iStart;
        this.yearList = [];
        for (let index = 0; index < 20; index++) {
          this.yearList.push(iStart + index);
        }
      },
      closePanel(e) {
        if (!this.showPanel) {
          return;
        }
        if (typeof e.target.className !== "string") {
          this.$nextTick(() => {
            this.showPanel = false;
          });
          return;
        }
        if (
          e.target.className.indexOf("_inner") === -1 ||
          (e.target.name === "yearInput" &&
            e.target !== this.$refs.inputLeft &&
            e.target !== this.$refs.inputRight)
        ) {
          this.$nextTick(() => {
            this.showPanel = false;
          });
        }

        e.stopPropagation();
        return false;
      },
      onClickLeft() {
        this.curYear = this.curYear * 1 - 10;
        this.updateYearList();
      },
      onClickRight() {
        this.curYear = this.curYear * 1 + 10;
        this.updateYearList();
      },
      setYear(startYearStamp, endYearStamp) {
        this.startShowYear = startYearStamp
        this.endShowYear = startYearStamp
        this.beginTime = startYearStamp
        this.endTime = startYearStamp
      }
      //------------------对外接口------------------------
      //直接传时间戳
      // setYear(startYearStamp, endYearStamp) {
      //   if (!isNaN(startYearStamp) && !isNaN(endYearStamp)) {
      //     let startYear = moment(startYearStamp).format("yyyy");
      //     let endYear = moment(endYearStamp).format("yyyy");
      //     this.startYear = startYear * 1;
      //     this.endYear = endYear * 1;
      //     this.endShowYear = endYear * 1;
      //     this.startShowYear = startYear * 1;
      //   }
      // },
    },

    created() {
      this.curYear = moment().format("yyyy");
      this.updateYearList();
    },
    beforeUnmount() {
      document.removeEventListener("click", this.closePanel.bind(this));
    },

    mounted() {
      this.$refs.yearPicker.style = "padding-left:" + this.labelWidth + "px";
      document.addEventListener("click", this.closePanel.bind(this));
    },
  };
</script>
<style lang="scss" scoped>
  .yearPicker {
    width: 260px;
    font-size: 14px;
    display: flex;
    position: relative;
    transition: all 0.3s;
    input:first-child {
      text-align: right;
    }
    .labelText {
      position: absolute;
      left: 8px;
    }
    background-color: #fff;
    span {
      padding: 0 8px;
      height: 32px;
      line-height: 32px;
    }
    border: 1px solid #eff1f3;
    height: 34px;
    line-height: 34px;
    border-radius: 4px;
    padding: 0 28px 0 8px;
    box-sizing: border-box;
    .floatPanel {
      > div {
        width: 50%;
      }
      padding: 0 16px;
      position: absolute;
      display: flex;
      background-color: #fff;
      z-index: 2000;
      border-radius: 4px;
      width: 650px;
      height: 250px;
      top: 40px;
      left: -50px;
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      .panelContent {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: calc(100% - 70px);
        .oneSelected {
          border-top-right-radius: 24px;
          border-bottom-right-radius: 24px;
        }
        .startSelected {
          background-color: #f6f6f7;
          border-top-left-radius: 24px;
          border-bottom-left-radius: 24px;
        }
        .endSelected {
          background-color: #f6f6f7;
          border-top-right-radius: 24px;
          border-bottom-right-radius: 24px;
        }
        .betweenSelected {
          background-color: #f6f6f7;
        }
        > div {
          width: 75px;
          height: 48px;
          line-height: 48px;
          margin: 3px 0;
          // border-radius: 24px;
          text-align: center;
          a {
            display: inline-block;
            width: 60px;
            height: 36px;
            cursor: pointer;
            line-height: 36px;
            border-radius: 18px;
          }
          .selected {
            background-color: #3e77fc;
            color: #fff;
          }
        }
      }
      .panelHead {
        position: relative;
        height: 46px;
        line-height: 46px;
        text-align: center;
        i {
          position: absolute;
          cursor: pointer;
          &:hover {
            color: #3e77fc;
          }
        }
      }
      .rightPanel {
        padding-left: 8px;
      }
      .leftPanel .panelHead i {
        left: 20px;
      }
      .rightPanel .panelHead i {
        right: 20px;
      }
    }
    .floatPanel::before {
      content: "";
      height: 100%;
      position: absolute;
      left: 50%;
      width: 1px;
      border-left: 1px solid #e4e4e4;
    }
  }
  input {
    width: 60px;
    border: none;
    height: 32px;
    line-height: 32px;
    box-sizing: border-box;
    background-color: transparent;
  }
  input:focus {
    outline: none;
    background-color: transparent;
  }
  .yearPicker:hover {
    border-color: #3e77fc;
  }
  .dateIcon {
    position: absolute;
    right: 16px;
    top: 9px;
    color: #adb2bc;
  }
</style>

​
